package com.manong.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manong.entity.DictType;
import com.manong.service.DictTypeService;
import com.manong.utils.Result;
import com.manong.vo.query.DictTypeQueryVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/dictType")
public class DictTypeController {
    @Resource
    private DictTypeService dictTypeService;
    /**
     * 查询所有字典类型列表
     */
    @GetMapping("/listAll")
    public Result listAll() {
        return Result.ok(dictTypeService.list());
    }
    /**
     * 分页查询字典类型列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:dictType:select')")
    public Result list(DictTypeQueryVo dictTypeQueryVo) {
        //创建分页信息
        IPage<DictType> page = new Page<DictType>(dictTypeQueryVo.getPageNo(), dictTypeQueryVo.getPageSize());
        //调用分页查询方法
        dictTypeService.findDictTypeListByPage(page, dictTypeQueryVo);
        //返回数据
        return Result.ok(page);
    }
    /**
     * 添加字典类型
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:dictType:add')")
    public Result add(@RequestBody DictType dictType){
        //调用保存字典类型的方法
        if(dictTypeService.save(dictType)){
            return Result.ok().message("字典类型添加成功");
        }
        return Result.error().message("字典类型添加失败");
    }
    /**
     * 修改字典类型
     */
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('sys:dictType:edit')")
    public Result update(@RequestBody DictType dictType){
        if(dictTypeService.updateById(dictType)){
            return Result.ok().message("字典类型修改成功");
        }
        return Result.error().message("字典类型修改失败");
    }
    /**
     * 删除字典类型
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:dictType:delete')")
    public Result delete(@PathVariable Long id) {
        //调用删除用户信息的方法
        if(dictTypeService.removeById(id)){
            return Result.ok().message("字典类型删除成功");
        }
        return Result.error().message("字典类型删除失败");
    }
    /**
     * 查询字典类型下是否有子表
     */
    @GetMapping ("/check/{dictType}")
    public Result check(@PathVariable String dictType){
        //调用查询该字典类型下是否有子表
        if (dictTypeService.checkDictType(dictType)){
            return Result.exist().message("该字典类型下面有子表，无法删除");
        }
        return Result.ok();
    }
}

